package com.business.common.exception;

import com.business.common.dto.R;
import com.business.common.enums.ErrorEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * @author chenjiehong
 * @Description:
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R defaultExceptionHandler(HttpServletRequest request, Exception e) {
        if (e instanceof CustomException) {
            logger.error("错误信息：", e.getMessage());
            CustomException customException = (CustomException) e;
            return R.error(customException.getCode(), customException.getMessage());
        } else if (e instanceof BusinessException) {
            logger.error("错误信息：", e.getMessage());
            BusinessException businessException = (BusinessException) e;
            return R.error(businessException.getCode(), businessException.getMessage());
        } else if (e instanceof SQLException) {
            logger.error("错误信息：", e.getMessage(), e);
            return R.error(ErrorEnum.SERVER_ERROR);
        } else {
            logger.error("错误信息：", e.getMessage(), e);
            return R.error(ErrorEnum.UNKNOWN_ERROR.getCode(), ErrorEnum.UNKNOWN_ERROR.getMsg(), e.getMessage());
        }
    }
}